<template>
    <div id="viewport"></div>
</template>
<script lang="ts" setup>
import { onMounted } from 'vue';
import { defaultSetting, add3dObjects, onPointerMove, saveState } from './index.ts';
import { editor } from '@/store';

let unsubscribeEditor: any = null;

onMounted(() => {

    const dom = document.getElementById('viewport') as HTMLElement;
    // 初始化3d场景
    defaultSetting(dom);
    // 添加拖拽事件
    addDropEvent(dom);
    // 添加鼠标、触摸和触控笔事件
    addPointerEvent(dom);

    unsubscribeEditor = addEditorActionsCallBack();
    // 初始化存储中的记录
    editor.storage.init(function () {
        // 初始化成功会立即执行
        console.log('storage.init');
        editor.storage.get(function (state: any) {
            console.log('storage.get', state);
            if (state) {
                editor.fromJSON(state);
            }
        });
    })
})

function addEditorActionsCallBack() {
    // 当组件被卸载时，它将被自动清理掉，如果要在卸载组件后保留它们，请将 { detached: true } 
    return editor.$onAction(({ name, after }) => {
        // 订阅editor下所有action
        if (name == 'addObject' || name == 'removeObject') {
            // `resolvedValue` 是 action 返回的值，如果是一个 Promise，它将是已经 resolved 的值
            after((resolvedValue: any) => {
                if (editor.subscribeActive) {
                    saveState();
                    console.log('订阅回调', name, resolvedValue);
                }
            })
        }
    })
}

function addDropEvent(dropZone: HTMLElement) {
    // 监听拖拽事件
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, (e: any) => {
            e.preventDefault();
            e.stopPropagation();
        }, false);
    });
    // 高亮显示放置区域
    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => {
            dropZone.classList.add('highlight');
        }, false);
    });
    // 移除高亮显示
    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => {
            dropZone.classList.remove('highlight');
        }, false);
    });
    // 处理文件上传
    dropZone.addEventListener('drop', (e: any) => {
        let files: any = e.dataTransfer.files;
        ([...files]).forEach(add3dObjects);
    }, false);
}

function addPointerEvent(dom: HTMLElement) {
    // 旨在将鼠标、触摸和触控笔事件整合
    // dom.addEventListener('pointerdown', onPointerDown);
    // dom.addEventListener('pointerup', onPointerUp);
    dom.addEventListener("pointermove", onPointerMove);
}

</script>

<style lang="scss" scoped type="text/css">
#viewport {
    width: 80% !important;
    height: calc(100% - $menubar_height) !important;
}

.highlight {
    border: 1px solid yellow;
}
</style>